package com.jader.fragment;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.activities.SouSuoActivity;
import com.jader.adapter.MerchantAdapter;
import com.jader.beans.Goods;
import com.jader.db.MyData;
import com.jader.myviews.MyProgressDialog;
import com.jader.util.JaderApplication;
import com.zlp.jader.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MerchantFragment extends Fragment implements IXListViewListener {

	private View view;
	private XListView merchantListView;
	private RequestQueue queue;
	private MerchantAdapter adapter;
	private List<Goods> list = new ArrayList<Goods>();
	private JaderApplication application;
	private JsonArrayRequest arrayRequest;
	private String url = JaderApplication.getIP() + "/Jader/client?type="
			+ JaderApplication.ALL_GOODS + "&page=";
	private int page = 0;
	private int result;
	private String time = null;
	private Activity activity;
	private int categoryid;
	private TextView top_title;
	private RadioGroup group;
	private RadioButton priceButton;
	private boolean flag = true;
	private int classification = 1;
	private ImageButton merchant_search;
	private MyProgressDialog dialog;
	private SQLiteDatabase sqLiteDatabase;

	@Override
	public void onAttach(Activity activity) {
		this.activity = activity;
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.activity_merchant, container, false);
		initViews();
		initData();
		return view;
	}

	private void initData() {
		getData();
		adapter = new MerchantAdapter(list, getActivity());
		merchantListView.setAdapter(adapter);
		merchantListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int position = arg2 - 1;
				if (position >= 0 && position <= list.size()) {
					Intent intent = new Intent(getActivity(),
							com.jader.activities.Seller.class);
					intent.putExtra("goods", list.get(position));
					startActivity(intent);
				}
			}
		});
	}

	private void getData() {
		if (categoryid == 0) {
			if (JaderApplication.isNetworkAvailable(getActivity())) {
				sendReques(url + page + "&classification=" + classification);
			} else {
				fail();
			}
		} else {
			sendReques(url + page + "&classification=" + classification
					+ "&categoryid=" + categoryid);
		}
	}

	private void initViews() {
		dialog = JaderApplication.getMyDialog(activity);
		merchantListView = (XListView) view.findViewById(R.id.merchant_list);
		top_title = (TextView) view.findViewById(R.id.merchant_top_title);
		group = (RadioGroup) view.findViewById(R.id.choice_layout);
		priceButton = (RadioButton) view.findViewById(R.id.price);
		merchant_search = (ImageButton) view.findViewById(R.id.merchant_search);
		merchantListView.setPullLoadEnable(true);
		merchantListView.setXListViewListener(this);
		merchant_search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(activity, SouSuoActivity.class);
				startActivity(intent);
			}
		});
		priceButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				boolean isChecked = priceButton.isChecked();
				if (isChecked) {
					if (flag) {
						priceButton.setText("价格最高");
						classification = 3;
						list.clear();
						result = 0;
						page = 0;
						getData();
						flag = false;
					} else {
						priceButton.setText("价格最低");
						classification = 4;
						list.clear();
						result = 0;
						page = 0;
						getData();
						flag = true;
					}
				}
			}
		});
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				switch (arg1) {
				case R.id.new_release:
					classification = 1;
					result = 0;
					page = 0;
					list.clear();
					getData();
					break;
				case R.id.popularity:
					classification = 2;
					result = 0;
					page = 0;
					list.clear();
					getData();
					break;
				default:
					break;
				}

			}
		});
		application = (JaderApplication) getActivity().getApplication();
		queue = application.getQueue();
		categoryid = activity.getIntent().getIntExtra("categoryid", 0);
		switch (categoryid) {
		case 1:
			top_title.setText("和田玉");
			break;
		case 2:
			top_title.setText("独山玉");
			break;
		case 3:
			top_title.setText("岫岩玉");
			break;
		case 4:
			top_title.setText("蓝田玉");
			break;
		default:
			break;
		}
	}

	private void onLoad() {
		merchantListView.stopRefresh();
		merchantListView.stopLoadMore();
		if (time == null) {
			merchantListView.setRefreshTime("刚刚");
		} else {
			merchantListView.setRefreshTime(time);
		}
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = df.format(date);
	}

	@Override
	public void onRefresh() {
		result = 0;
		page = 0;
		getData();
	}

	@Override
	public void onLoadMore() {
		page = list.size();
		result = list.size();
		getData();
	}

	private void sendReques(String url) {
		if (JaderApplication.isNetworkAvailable(getActivity())) {
			dialog.show();
			arrayRequest = new JsonArrayRequest(url,
					new Response.Listener<JSONArray>() {

						@Override
						public void onResponse(JSONArray response) {
							onLoad();
							Gson gson = new Gson();
							// TypeToken内的泛型就是Json数据中的类型
							Type listType = new TypeToken<ArrayList<Goods>>() {
							}.getType();
							List<Goods> arrayList = gson.fromJson(
									response.toString(), listType);
							for (Goods user : arrayList) {
								boolean flag = true;
								for (Goods user2 : list) {
									if (user.equals(user2)) {
										flag = false;
									}
								}
								if (flag) {
									list.add(result, user);
									result++;
								}
							}
							adapter.notifyDataSetChanged();
							if (dialog.isShowing()) {
								dialog.dismiss();
							}
						}

					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							fail();
						}
					});
			queue.add(arrayRequest);
		} else {
			fail();
		}
	}

	private void fail() {
		onLoad();
		JaderApplication.show(getActivity(), "网络访问失败，请检查网络连接或刷新");
		dialog.dismiss();
		if (categoryid == 0) {
			onLoad();
			sqLiteDatabase = JaderApplication.getSqLiteDatabase();
			String sql = "select * from " + MyData.GOODSLIST_MERCHANT_TABLE;
			Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
			list.clear();
			while (cursor.moveToNext()) {
				int i = 0;
				if (i >= 20) {
					break;
				}
				int msg = cursor.getInt(0);
				String desc = cursor.getString(1);
				double price = cursor.getDouble(2);
				String picture = cursor.getString(3);
				String goodsname = cursor.getString(4);
				list.add(new Goods(null,msg, 0, goodsname, price, desc, null,
						picture, 0, 0));
				i++;

			}

			sqLiteDatabase.close();
		}
	}

	@Override
	public void onPause() {
		if (categoryid == 0) {
			sqLiteDatabase = JaderApplication.getSqLiteDatabase();
			String delete = "delete from " + MyData.GOODSLIST_MERCHANT_TABLE;
			sqLiteDatabase.execSQL(delete);
			sqLiteDatabase.close();
			for (int i = 0; i < 20; i++) {
				if (i < list.size()) {
					Goods good = list.get(i);
					sqLiteDatabase = JaderApplication.getSqLiteDatabase();
					String sql = "insert into "
							+ MyData.GOODSLIST_MERCHANT_TABLE
							+ " values(?,?,?,?,?)";
					String[] texts = { good.getGoodsid() + "", good.getDesc(),
							good.getPrice() + "", good.getPicture(),
							good.getGoodsName() };
					if (texts != null) {
						sqLiteDatabase.execSQL(sql, texts);
					}
					sqLiteDatabase.close();
				}
			}
		}
		super.onPause();
	}

}
